<template>
  <div id="sale-panel">
    <transition name="fade">
      <div class="container">
        <div class="header-box">
          <div class="title">上架艺术品</div>
          <div class="close-btn">
            <el-button
              class="close-btn"
              plain
              size="small"
              icon="el-icon-close"
              circle
              @click="$emit('close')"
            ></el-button>
          </div>
        </div>
        <div class="main-box">
          <div class="left-container">
            <!-- 拍卖形式 -->
            <div class="sale-type">
              <div class="tip">拍卖形式</div>
              <div class="hint">
                选择拍卖形式，定价交易为直接交易；拍卖则为竞价出售，需要设置起始价格
              </div>
              <div>
                <el-radio-group
                  fill="#F38181"
                  size="small"
                  v-model="formParams.saleType"
                >
                  <el-radio-button label="定价出售"></el-radio-button>
                  <el-radio-button label="拍卖"></el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <!-- 拍卖价格 -->
            <div class="price">
              <template v-if="formParams.saleType == '拍卖'" class="tip"
                ><div class="price-tip tip-need">起始价：</div></template
              >
              <template v-else>
                <div class="price-tip tip-need">售价：</div>
              </template>
              <el-input
                class="price-input"
                v-model="formParams.price"
                placeholder="价格"
                type="number"
                :min="0"
              ></el-input>
              <el-select
                style="width: 100px"
                v-model="formParams.unit"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in units"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <!-- 拍卖场次 -->
            <div class="bid-session" v-if="formParams.saleType == '拍卖'">
              <div class="tip">
                选择拍卖日期
                <el-date-picker
                  v-model="formParams.auctionDate"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="timestamp"
                  class="action-date-picker"
                  :start-placeholder="'2022-3-27'"
                  :picker-options="pickerOptions"
                  @change="changeDate"
                >
                </el-date-picker>
              </div>
              <div class="session-box">
                <div class="tip">选择拍卖的场次</div>
                <div class="session">
                  <div
                    class="session-item"
                    @click="selectSession(item.id)"
                    v-for="item in sessions"
                    :key="item.id"
                    :class="{ 'session-active': item.selected }"
                  >
                    {{ item.title }}
                  </div>
                  <div class="session-tip" v-if="sessions.length < 1">
                    当天没有拍卖场次
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right-container">
            <div class="summary-box">
              <div class="summary-header">总计</div>
              <div class="summary-price">
                <div class="summary-price-tip">价格：</div>
                <div class="eth-icon">
                  <img src="./images/ethereum.png" alt="" />
                </div>
                <div class="summary-true-price">{{ truePrice }}</div>
              </div>
              <div
                class="summary-session-box"
                v-if="formParams.saleType == '拍卖'"
              >
                <div class="summary-session-tip">拍卖场次</div>
                <div class="summary-session-text">
                  {{ selectedSession.label }}
                </div>
              </div>
              <!-- 费用 -->
              <div class="fees-box">
                <div class="fees-header">手续费</div>
                <div class="platform-fees">
                  <div>平台费用</div>
                  <div class="gap"></div>
                  <div>2%</div>
                </div>
              </div>
              <!-- 按钮组 -->
              <div class="btn-group">
                <div class="comfirm-btn btn" @click="mint">上架</div>
                <div class="cansel-btn btn" @click="$emit('close')">取消</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { queryAuctionByDate } from "@/api";
import moment from "moment";
import web3 from "web3";
import getAbi from "@/utils/contractAbi";
export default {
  name: "SalePanel",
  props: ["artDetail"],
  inject: ["reload"],
  data() {
    return {
      formParams: {
        saleType: "定价出售",
        price: "0",
        unit: "ETH",
        auctionDate: "",
      },
      //   价格单位
      units: [
        { label: "ETH", value: "ETH", selected: true },
        { label: "Wei", value: "Wei", selected: false },
      ],

      // 时间段
      sessions: [],
      // 选中的单位
      selectedUnit: "ETH",

      // 禁用日期
      pickerOptions: {
        disabledDate(time) {
          // console.log(this, 'this') // 访问不到this
          return time.getDate() <= new Date().getDate() - 1;
        },
      },
    };
  },
  computed: {
    ...mapState({
      isShowSale: (store) => store.popPanel.isShowSale,
    }),
    // 实际价格
    truePrice() {
      if (this.formParams.unit == "ETH") {
        return this.formParams.price;
      } else if (this.formParams.unit == "Wei") {
        this.formParams.price = parseInt(this.formParams.price).toString();
        return web3.utils.fromWei(this.formParams.price, "ether");
      }
    },

    // 选中的场次
    selectedSession() {
      let t = {};
      this.sessions.forEach((item) => {
        if (item.selected) {
          t.label =
            moment(this.formParams.auctionDate).format("YYYY-MM-DD") +
            "  " +
            item.title;
          t.startTime = parseInt(new Date(item.starttime).getTime() / 1000);
          t.endTime = parseInt(new Date(item.endtime).getTime() / 1000);
          t.auctionId = item.id;
        }
      });
      return t;
    },
  },

  methods: {
    // 修改日期
    async changeDate(time) {
      let dateString = moment(time).format("YYYY-MM-DD");
      // 查询拍卖场次
      let result = await queryAuctionByDate(dateString);
      if (result.flag == false) {
        this.sessions = [];
        return;
      }
      result.forEach((item) => {
        item.selected = false;
      });
      this.sessions = result;
    },

    selectSession(id) {
      this.sessions.forEach((item) => {
        if (item.id == id) {
          item.selected = true;
        } else {
          item.selected = false;
        }
      });
    },

    // 调用合约上架
    async mint() {
      let { price, saleType, unit } = this.formParams;
      // 校验
      if (price == "0") {
        this.$message.error("价格不能为0");
        return;
      }
      if (saleType == "拍卖") {
        if (this.selectedSession.auctionId == null) {
          this.$message.error("未选择拍卖时间");
          return;
        }
      }
      // 价格转换
      if (unit == "ETH") {
        price = parseInt(web3.utils.toWei(price, "ether"));
        web3.eth;
      } else {
        price = parseInt(price);
      }

      let abi = await getAbi();
      let nft_id = this.artDetail.nft_id;
      // 如果nftid为空，则为首次销售
      if (nft_id == null) {
        let { id, title, shop_hash, info, classify, commission } =
          this.artDetail;
        let worksId = id;
        let Name = title;
        let artWorkHash = shop_hash;
        let desc = info;
        let category = classify;
        let user_address = this.$store.getters.user_address;
        commission = commission * 100;

        // 调用合约
        // console.log(abi)
        
        if (saleType == "定价出售") {
          abi.methods
            ._mint(
              worksId,
              Name,
              artWorkHash,
              desc,
              price.toString(),
              category,
              commission
            )
            .send({ from: user_address })
            .then((res) => {
              console.log(res)
              this.$message.success("上架成功");
              this.$emit("close");
              // 刷新页面
              this.reload();
            })
            .catch((err) => {
              this.$message.error("交易错误，请重试");
            });
        } else if (saleType == "拍卖") {
          let auctionStartTime = this.selectedSession.startTime;
          let auctionEndTime = this.selectedSession.endTime;
          let auctionId = this.selectedSession.auctionId;
          abi.methods
            ._mint(
              worksId,
              Name,
              artWorkHash,
              desc,
              price.toString(),
              category,
              commission,
              auctionStartTime,
              auctionEndTime,
              auctionId
            )
            .send({ from: user_address })
            .then(() => {
              this.$message.success("上架成功");
              this.$emit("close");
              this.reload()
            })
            .catch(() => {
              this.$message.error("交易错误，请重试");
            });
        }
      }else{
        // 二次销售
        // 一口价
        console.log('二次')
        let user_address = this.$store.getters.user_address;
        abi.methods.startSecondSale(nft_id, price.toString()).send({
          from:user_address
        }).then(()=>{
          this.$message.success("上架成功")
          this.$emit('close')
          this.reload()
        }).catch(()=>{
          this.$message.error("交易错误，请重试")
        })
      }
    },
  },
};
</script>

<style lang='less'>
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  transform: translateY(50vh);
}
// 响应式布局
@media screen and (max-width: 880px) {
  #sale-panel {
    .main-box {
      display: block !important;
      .right-container {
        margin: 20px 0 !important;
      }
    }
  }
}
#sale-panel {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.2);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  .container {
    background: #fff;
    padding: 30px;
    border-radius: 10px;

    .header-box {
      margin: 0;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 20px;
        font-weight: bold;
      }
    }
    .tip {
      font-size: 14px;
      margin-bottom: 5px;
    }
    .tip-need::before {
      content: "*";
      color: red;
      margin-right: 5px;
    }
    .hint {
      margin-bottom: 5px;
      font-size: 12px;
      color: #999;
    }
    .main-box {
      display: flex;
      justify-content: space-between;
      .left-container {
        .sale-type {
          .el-radio-button__inner:hover {
            color: var(--themeColor1);
            opacity: 0.5;
            transition: 0.5s ease;
          }
          .is-active {
            .el-radio-button__inner:hover {
              color: #fff;
            }
          }
        }
        .price {
          margin-top: 35px;
          display: flex;
          align-items: center;
          .price-tip {
            white-space: nowrap;
          }
          .price-input {
            width: 180px;
          }
        }

        .bid-session {
          margin-top: 20px;
          .action-date-picker {
            display: block;
            margin-top: 10px;
          }
          .session-box {
            margin-top: 20px;
            .session {
              margin-top: 10px;
              display: flex;
              flex-wrap: wrap;
              .session-active {
                color: #fff;
                background: var(--themeColor1);
              }
              .session-item {
                font-size: 14px;
                cursor: pointer;
                margin-right: 20px;
                box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.05);
                padding: 8px 10px;
                border-radius: 99px;
                transition: all 0.2s ease;
              }
              .session-item:hover {
                color: #fff;
                background: var(--themeColor1);
              }
              .session-tip {
                font-size: 14px;
                color: #999;
              }
            }
          }
        }
      }
      .right-container {
        margin-left: 30px;
        padding: 20px;
        border-radius: 10px;
        width: 400px;
        .summary-box {
          .summary-header {
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
          }
          .summary-price {
            padding: 20px 0;
            display: flex;
            align-items: center;
            .eth-icon {
              height: 15px;
              width: 15px;
              img {
                width: 100%;
                height: 100%;
              }
            }
            .summary-price-tip {
              margin-left: 10px;
              font-size: 14px;
              color: #666;
              width: 50px;
            }
            .summary-true-price {
              margin-left: 10px;
              font-size: 18px;
            }
          }
          .summary-session-box {
            padding: 10px 0;
            border-top: 1px solid #eee;
            .summary-session-tip {
              font-size: 14px;
              color: #666;
            }
            .summary-session-text {
              margin-top: 5px;
              font-size: 16px;
            }
          }
          .fees-box {
            padding-top: 10px;
            border-top: 1px solid #eee;
            .fees-header {
              font-size: 14px;
            }
            .platform-fees {
              color: #666;
              margin-top: 10px;
              display: flex;
              align-items: center;
              font-size: 12px;
              .gap {
                flex: 1;
                border-bottom: 1px dashed #666;
                margin: 0 10px;
              }
            }
          }

          .btn-group {
            margin-top: 20px;
            border-top: 1px solid #eee;
            padding-top: 20px;
            display: flex;
            align-items: center;
            .btn {
              cursor: pointer;
              padding: 8px 20px;
              margin-right: 10px;
              border-radius: 99px;
            }
            .btn:hover {
              opacity: 0.7;
            }
            .comfirm-btn {
              background: var(--themeColor1);
              color: #fff;
            }
            .cansel-btn {
              border: 1px solid #eee;
              color: #333;
            }
          }
        }
      }
    }
  }
}
</style>